<template>
  <a-card title="溯源详情" style="margin-top: 10px">
    <a-row>
      <a-col :md="16" :sm="24">
        <a-form-model
            ref="traceAddForm"
            :model="data"
            :rules="rules"
            :label-col="{span: 4}"
            :wrapper-col="{span: 14}">
          <a-form-item label="选择园区" prop="farmId">
            <a-select label-in-value placeholder="请选择园区" allowClear @change="farmChange">
              <a-select-option
                  v-for="(item, index) in farmList"
                  :key="index" :value="item.FarmId">
                {{item.FarmName}}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="选择地块" prop="houseId">
            <a-select label-in-value placeholder="请选择地块" :value="{key: data.houseId}" allowClear @change="houseChange">
              <a-select-option
                  v-for="(item, index) in greenHouseList"
                  :key="index" :value="item.GreenHouseId">
                {{item.GreenHouseName}}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-model-item label="页面标题" prop="company">
            <a-input v-model="data.company" placeholder="请输入页面标题" type="text" allowClear/>
          </a-form-model-item>
          <a-form-model-item label="地块类型" prop="houseType">
            <a-input v-model="data.houseType" placeholder="请输入地块类型" type="text" allowClear/>
          </a-form-model-item>
          <a-form-model-item label="作物名称" prop="plantName">
            <a-input v-model="data.plantName" placeholder="请输入作物名称" type="text" allowClear/>
          </a-form-model-item>
          <a-form-model-item label="种植日期" prop="plantDate">
            <a-date-picker
                v-model="data.plantDate"
                type="date"
                placeholder="选择种植日期"
                style="width: 200px;"
                @change="dateChange"
            />
          </a-form-model-item>
          <a-form-model-item label="种植面积" prop="size">
            <a-input v-model="data.size" placeholder="请输入种植面积" type="text" allowClear/>
          </a-form-model-item>
          <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
            <a-button type="primary" @click="sub">
              提交
            </a-button>
            <a-button style="margin-left: 10px;" @click="reset">
              重置
            </a-button>
          </a-form-model-item>
        </a-form-model>
      </a-col>
      <a-col :md="8" :sm="24">
        <div class="admin-list">
          <a-table :columns="columns" :data-source="owners"
                   :rowKey="(data, index) => index"
                   :pagination="false" bordered>
            <template slot="title">
              管理员信息
            </template>
            <template slot="footer">
              <div class="admin-add">
                <div class="add-name">选择管理员</div>
                <div class="add-list">
                  <a-select placeholder="请选择管理员" style="width: 200px" label-in-value @change="selectManager" allowClear>
                    <a-select-option
                        v-for="(item, index) in managerList"
                        :key="index" :value="index">
                      {{fullManager(item)}}
                    </a-select-option>
                  </a-select>
                </div>
                <div class="add-btn" @click="addManager"><a-icon type="plus"/>添加</div>
              </div>
            </template>
            <span slot="action" slot-scope="text, record, index">
                   <a-popconfirm title="确定删除?" @confirm="delRecord(record, index)">
                    <a-icon slot="icon" type="question-circle-o" style="color: red" />
                    <a href="#" style="color: #f5222d"><a-icon type="delete" />删除</a>
                  </a-popconfirm>
               </span>
          </a-table>
        </div>
      </a-col>
    </a-row>
  </a-card>
</template>

<script>
  import { FormModel } from 'ant-design-vue';
  import {list as farmList} from '@/services/farm'
  import { list as greenHouseList } from '@/services/greenhouse'
  import { list as managerList} from '@/services/manager'
  import {add} from '@/services/trace'
  const columns = [
    {
      title: '昵称',
      dataIndex: 'owner',
      width: '30%',
      scopedSlots: { customRender: 'owner' },
    },
    {
      title: '手机号码',
      dataIndex: 'ownerPhone',
      width: '50%',
      scopedSlots: { customRender: 'ownerPhone' },
    },{
      title: '操作',
      dataIndex: 'action',
      scopedSlots: { customRender: 'action' },
    }
  ];
  export default {
    name: "TraceAdd",
    data() {
      return {
        columns,
        owners: [],
        ownersCache: {}, //添加管理员
        loading: false,
        farmList: [],
        greenHouseList: [],
        managerList: [],
        data: {
          farmId: '',
          houseId: '',
          company: 'YesIoT 智慧农业溯源系统',
          size: ''
        },
        rules: {
          company: [
            { required: true, message: '请输入页面标题', trigger: 'blur' }
          ],
          plantDate: [
            { required: true, message: '请选择种植日期', trigger: 'change' }
          ],
          plantName: [
            { required: true, message: '请输入作物名称', trigger: 'blur' }
          ],
          size: [
            { required: true, message: '请输入种植面积', trigger: 'blur' }
          ]
        }
      }
    },
    computed: {
      fullManager(obj) {
        let name = ''
        return obj => {
          if(obj.AdminName) {
            name =  `${obj.Phone},${obj.AdminName}`
          } else name = obj.Phone
          return name
        }
      }
    },
    components: {
      FormModel
    },
    created() {
      this.getFarmList()
    },
    methods: {
      async getFarmList() {
        let res = await farmList()
        this.farmList = res.Data
      },
      async getManagerList() {
        let res = await managerList(this.data.farmId)
        this.managerList = res.Data
      },
      async getGreenHouseList() {
        let res = await greenHouseList(this.data.farmId)
        this.greenHouseList = res.Data
      },
      sub() {
        if(this.data.farmId == '') {
          this.$message.error('请选择园区')
          return
        }
        if(this.data.houseId == '') {
          this.$message.error('请选择地块')
          return
        }
        this.$refs.traceAddForm.validate(valid => {
          if (valid) {
            if(this.owners.length == 0) {
              this.$message.warning('请添加管理员')
              return
            }
            this.data.owners = this.owners
            console.log(this.data);
            add(this.data).then(res => {
              if(res.Code == 0) {
                this.$message.success('创建成功')
                Object.assign(this.$data, this.$options.data())
              } else this.$message.error('创建失败')
            }).catch(err => {
              console.log(err)
              this.$message.error('创建失败')
            })
          }
        })
      },
      farmChange(obj) {
        this.data.farmId = obj.key
        this.data.farmName = obj.label
        this.data.houseId = ''
        this.getGreenHouseList()
        this.getManagerList()
      },
      houseChange(obj) {
        this.data.houseId = obj.key
        this.data.houseName = obj.label
      },
      selectManager(obj) {
        const labelArr = obj.label.split(',')
        this.ownersCache.ownerPhone = labelArr[0]
        this.ownersCache.owner = labelArr.length == 2 ? labelArr[1] : '' //带昵称
      },
      dateChange(e, v) {
        console.log(v);
        this.data.plantDate = v
      },
      addManager() {
        const ownerInfo = {...this.ownersCache} //深度复制
        if(!ownerInfo.ownerPhone) {
          this.$message.error('未选择')
          return
        }
        const index = this.owners.findIndex(item => item.ownerPhone == ownerInfo.ownerPhone)
        if(index == -1) {
          this.owners.push(ownerInfo)
        } else this.$message.warning('此管理员已存在')
      },
      delRecord(row, index) {
        if(!row.ownerPhone) {
          this.$message.error('无效管理员')
          return
        }
        console.log(index);
        this.owners.splice(index, 1)
      },
      reset() {
        Object.assign(this.$data, this.$options.data())
        this.getFarmList()
      }
    }
  }
</script>

<style lang="less" scoped>
  .admin-add {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .add-btn {
      color: rgb(0, 205, 0);
      cursor: pointer;
    }
    .add-list {
      flex: 1;
      margin:0 20px;
    }
  }
</style>
